package cn.powerone.scm.upload.service.impl;

import java.util.List;

import cn.powerone.common.exception.ServiceException;
import cn.powerone.common.utils.DateUtils;
import cn.powerone.common.utils.StringUtils;
import cn.powerone.scm.domain.ScmInquiriesIn;
import cn.powerone.scm.domain.ScmProducts;
import cn.powerone.scm.domain.ScmProjectProducts;
import cn.powerone.scm.mapper.ScmInquiriesInMapper;
import cn.powerone.scm.mapper.ScmProductsMapper;
import cn.powerone.scm.mapper.ScmProjectProductsMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import cn.powerone.scm.upload.mapper.ScmImportInquiriesInMapper;
import cn.powerone.scm.upload.domain.ScmImportInquiriesIn;
import cn.powerone.scm.upload.service.IScmImportInquiriesInService;

/**
 * 导入询价BatchService业务层处理
 * 
 * @author PowerOne
 * @date 2025-07-07
 */
@Service
public class ScmImportInquiriesInServiceImpl implements IScmImportInquiriesInService 
{
    @Autowired
    private ScmImportInquiriesInMapper scmImportInquiriesInMapper;
    @Autowired
    private ScmProductsMapper scmProductsMapper;
    @Autowired
    private ScmProjectProductsMapper scmProjectProductsMapper;
    @Autowired
    private ScmInquiriesInMapper scmInquiriesInMapper;

    /**
     * 查询导入询价Batch
     * 
     * @param id 导入询价Batch主键
     * @return 导入询价Batch
     */
    @Override
    public ScmImportInquiriesIn selectScmImportInquiriesInById(Long id)
    {
        return scmImportInquiriesInMapper.selectScmImportInquiriesInById(id);
    }

    /**
     * 查询导入询价Batch列表
     * 
     * @param scmImportInquiriesIn 导入询价Batch
     * @return 导入询价Batch
     */
    @Override
    public List<ScmImportInquiriesIn> selectScmImportInquiriesInList(ScmImportInquiriesIn scmImportInquiriesIn)
    {
        return scmImportInquiriesInMapper.selectScmImportInquiriesInList(scmImportInquiriesIn);
    }

    /**
     * 新增导入询价Batch
     * 
     * @param scmImportInquiriesIn 导入询价Batch
     * @return 结果
     */
    @Override
    public int insertScmImportInquiriesIn(ScmImportInquiriesIn scmImportInquiriesIn)
    {
        scmImportInquiriesIn.setCreateTime(DateUtils.getNowDate());
        return scmImportInquiriesInMapper.insertScmImportInquiriesIn(scmImportInquiriesIn);
    }

    /**
     * 修改导入询价Batch
     * 
     * @param scmImportInquiriesIn 导入询价Batch
     * @return 结果
     */
    @Override
    public int updateScmImportInquiriesIn(ScmImportInquiriesIn scmImportInquiriesIn)
    {
        scmImportInquiriesIn.setUpdateTime(DateUtils.getNowDate());
        return scmImportInquiriesInMapper.updateScmImportInquiriesIn(scmImportInquiriesIn);
    }

    /**
     * 批量删除导入询价Batch
     * 
     * @param ids 需要删除的导入询价Batch主键
     * @return 结果
     */
    @Override
    public int deleteScmImportInquiriesInByIds(Long[] ids)
    {
        return scmImportInquiriesInMapper.deleteScmImportInquiriesInByIds(ids);
    }

    /**
     * 删除导入询价Batch信息
     * 
     * @param id 导入询价Batch主键
     * @return 结果
     */
    @Override
    public int deleteScmImportInquiriesInById(Long id)
    {
        return scmImportInquiriesInMapper.deleteScmImportInquiriesInById(id);
    }

    /** 导入数据
     * @param list 导入询价Batch列表
     */
    @Override
    public String importData(List<ScmImportInquiriesIn> list, Boolean isUpdateSupport, String operName, Long projectId) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ScmImportInquiriesIn item : list)
        {
            item.setProjectId(projectId);
            if (!scmImportInquiriesInMapper.selectScmImportInquiriesInList(item).isEmpty()){
                continue;
            }
            scmImportInquiriesInMapper.insertScmImportInquiriesIn(item);
            successNum++;
//            try
//            {
//                // 验证是否存在这个用户.
//                ScmImportInquiriesIn u = userMapper.selectUserByUserName(user.getUserName());
//                if (StringUtils.isNull(u))
//                {
//                    BeanValidators.validateWithException(validator, user);
//                    deptService.checkDeptDataScope(user.getDeptId());
//                    String password = configService.selectConfigByKey("sys.user.initPassword");
//                    user.setPassword(SecurityUtils.encryptPassword(password));
//                    user.setCreateBy(operName);
//
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
//                }
//                else if (isUpdateSupport)
//                {
//                    BeanValidators.validateWithException(validator, user);
//                    checkUserAllowed(u);
//                    checkUserDataScope(u.getUserId());
//                    deptService.checkDeptDataScope(user.getDeptId());
//                    user.setUserId(u.getUserId());
//                    user.setUpdateBy(operName);
//                    userMapper.updateUser(user);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
//                }
//                else
//                {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
//                }
//            }
//            catch (Exception e)
//            {
//                failureNum++;
//                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
//                failureMsg.append(msg + e.getMessage());
//                log.error(msg, e);
//            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    @Override
    @Async
    public void processImportData(){
        List<ScmImportInquiriesIn>  dataList =   scmImportInquiriesInMapper.selectScmImportInquiriesInList(new ScmImportInquiriesIn());
        ScmProducts scmProducts;
        ScmProjectProducts scmProjectProducts;
        ScmInquiriesIn scmInquiriesIn;
        for (ScmImportInquiriesIn scmImportInquiriesIn : dataList) {
            //查询产品表by drawing_number，产品是否存在，如果存在则获取产品ID，不存在则插入到产品表 获取产品ID
            scmProducts = scmProductsMapper.selectScmProductsByDrawingNumber(scmImportInquiriesIn.getDrawingNumber());
            if(scmProducts == null){
                scmProducts = new ScmProducts();
                scmProducts.setDrawingNumber(scmImportInquiriesIn.getDrawingNumber());
                scmProducts.setVersion(scmImportInquiriesIn.getVersion());
                scmProducts.setInternalVersion(scmImportInquiriesIn.getInternalVersion());
                scmProducts.setProductName(scmImportInquiriesIn.getProductName());
                scmProducts.setProductStatus(1L);
                scmProducts.setMaterial(scmImportInquiriesIn.getMaterial());
                scmProducts.setInflamingRetardingLevel(scmImportInquiriesIn.getInflamingRetardingLevel());
                scmProducts.setSpecification(scmImportInquiriesIn.getSpecification());
                scmProducts.setModel(scmImportInquiriesIn.getModel());
                scmProducts.setColor(scmImportInquiriesIn.getColor());
                scmProducts.setDrawingComposition(scmImportInquiriesIn.getDrawingComposition());
                scmProducts.setProductRemark(scmImportInquiriesIn.getProductRemark());
                scmProductsMapper.insertScmProducts(scmProducts);
            }

            //查询项目产品表by project_id,product_id
            scmProjectProducts = scmProjectProductsMapper.selectScmProjectProductsByProjectIdAndProductId(scmImportInquiriesIn.getProjectId(),scmProducts.getId());
            //组装产品信息并插入项目产品连接表
            if (scmProjectProducts == null){
                scmProjectProducts = new ScmProjectProducts();
                scmProjectProducts.setProjectId(scmImportInquiriesIn.getProjectId());
                scmProjectProducts.setProductId(scmProducts.getId());
                scmProjectProducts.setDemandType(scmImportInquiriesIn.getDemandType());
                scmProjectProducts.setPurchaseCategory(scmImportInquiriesIn.getPurchaseCategory());
                scmProjectProducts.setCustomerStatus(1L);
                scmProjectProducts.setSupplierStatus(1L);
                scmProjectProducts.setProjectProductStatus(3L);
                scmProjectProducts.setDrawingNumber(scmImportInquiriesIn.getDrawingNumber());
                scmProjectProducts.setVersion(scmProducts.getVersion());
                scmProjectProducts.setInternalVersion(scmProducts.getInternalVersion());
                scmProjectProducts.setProductName(scmImportInquiriesIn.getProductName());
                scmProjectProducts.setMaterial(scmImportInquiriesIn.getMaterial());
                scmProjectProducts.setInflamingRetardingLevel(scmImportInquiriesIn.getInflamingRetardingLevel());
                scmProjectProducts.setSpecification(scmImportInquiriesIn.getSpecification());
                scmProjectProducts.setModel(scmImportInquiriesIn.getModel());
                scmProjectProducts.setColor(scmImportInquiriesIn.getColor());
                scmProjectProducts.setDrawingComposition(scmImportInquiriesIn.getDrawingComposition());
                scmProjectProductsMapper.insertScmProjectProducts(scmProjectProducts);
            }

            //查询项目询价信息by project_id,product_id
            scmInquiriesIn = scmInquiriesInMapper.selectScmInquiriesInByProjectIdAndProductId(scmImportInquiriesIn.getProjectId(),scmProducts.getId());
            //组装项目询价信息并插入项目询价表
            if (scmInquiriesIn == null){
                scmInquiriesIn = new ScmInquiriesIn();
                scmInquiriesIn.setProjectId(scmImportInquiriesIn.getProjectId());
                scmInquiriesIn.setProductId(scmProducts.getId());
                scmInquiriesIn.setProjectProductId(scmProjectProducts.getId());
                scmInquiriesIn.setDrawingNumber(scmProducts.getDrawingNumber());
                scmInquiriesIn.setInternalVersion(scmProducts.getInternalVersion());
                scmInquiriesIn.setMaterial(scmImportInquiriesIn.getMaterial());
                scmInquiriesIn.setSpecification(scmImportInquiriesIn.getSpecification());
                scmInquiriesIn.setColor(scmImportInquiriesIn.getColor());
                scmInquiriesIn.setOnceQuantity(scmImportInquiriesIn.getOnceQuantity());
                scmInquiriesIn.setOnceUnit(scmImportInquiriesIn.getOnceUnit());
                scmInquiriesIn.setMonthlyQuantity(scmImportInquiriesIn.getMonthlyQuantity());
                scmInquiriesIn.setMonthlyUnit(scmImportInquiriesIn.getMonthlyUnit());
                scmInquiriesIn.setYearlyQuantity(scmImportInquiriesIn.getYearlyQuantity());
                scmInquiriesIn.setYearlyUnit(scmImportInquiriesIn.getYearlyUnit());
                scmInquiriesIn.setDisposableQuantity(scmImportInquiriesIn.getDisposableQuantity());
                scmInquiriesIn.setDisposableUnit(scmImportInquiriesIn.getDisposableUnit());
                scmInquiriesIn.setDisposableUnitPrice(scmImportInquiriesIn.getDisposableUnitPrice());
                scmInquiriesIn.setDisposableExpectedDeliveryDate(scmImportInquiriesIn.getDisposableExpectedDeliveryDate());
                scmInquiriesIn.setDisposableTryQuantity(scmImportInquiriesIn.getDisposableTryQuantity());
                scmInquiriesIn.setDisposableTryUnit(scmImportInquiriesIn.getDisposableTryUnit());
                scmInquiriesIn.setDisposableTryUnitPrice(scmImportInquiriesIn.getDisposableTryUnitPrice());
                scmInquiriesIn.setDisposableTryExpectedDeliveryDate(scmImportInquiriesIn.getDisposableTryExpectedDeliveryDate());
                scmInquiriesIn.setTryQuantity(scmImportInquiriesIn.getTryQuantity());
                scmInquiriesIn.setTryUnit(scmImportInquiriesIn.getTryUnit());
                scmInquiriesIn.setTryUnitPrice(scmImportInquiriesIn.getTryUnitPrice());
                scmInquiriesIn.setTryExpectedDeliveryDate(scmImportInquiriesIn.getTryExpectedDeliveryDate());
                scmInquiriesIn.setMassQuantity(scmImportInquiriesIn.getMassQuantity());
                scmInquiriesIn.setMassUnit(scmImportInquiriesIn.getMassUnit());
                scmInquiriesIn.setMassUnitPrice(scmImportInquiriesIn.getMassUnitPrice());
                scmInquiriesIn.setMassExpectedDeliveryDate(scmImportInquiriesIn.getMassExpectedDeliveryDate());
                scmInquiriesIn.setExpectedQuotationDate(scmImportInquiriesIn.getExpectedQuotationDate());
                scmInquiriesIn.setExpectedDeliveryDate(scmImportInquiriesIn.getExpectedDeliveryDate());
                scmInquiriesIn.setExpectedDatum(scmImportInquiriesIn.getExpectedDatum());
                scmInquiriesIn.setRemarks(scmImportInquiriesIn.getRemarks());
                scmInquiriesInMapper.insertScmInquiriesIn(scmInquiriesIn);
            }
            //删除import表数据
            scmImportInquiriesInMapper.deleteScmImportInquiriesInByIds(new Long[]{scmImportInquiriesIn.getId()});
        }
    }
}
